// 使用动态导入兼容 node-fetch v3 (ES Module) 在 CommonJS 环境中
let fetch
;(async () => {
  const nodeFetch = await import('node-fetch')
  fetch = nodeFetch.default
})()
const { HttpsProxyAgent } = require('https-proxy-agent')

/**
 * 通过代理发送 fetch 请求
 * @param {string} targetUrl - 要访问的目标URL
 * @param {string} proxyUrl - 代理服务器地址 (如: 'http://proxy.example.com:8080')
 * @param {number} [timeout=5000] - 超时时间(毫秒)
 * @returns {Promise<Response>}
 */

/**
 * 检查代理是否可用
 * @param {string} proxyUrl - 代理地址 (如: 'http://123.123.123.123:8080')
 * @param {number} [timeout=3000] - 超时时间
 * @returns {Promise<boolean>}
 */
export async function isProxyValid(proxyUrl) {
  try {
    const data = await testProxy(proxyUrl)
    // 验证返回的IP是否是代理IP
    const proxyHost = new URL(proxyUrl).hostname
    return data.yourIp.includes(proxyHost)
  } catch (error) {
    console.error(`代理 ${proxyUrl} 不可用:`, error.message)
    return false
  }
}
// 批量测试代理池的方法
export async function testProxyPool(proxyList, concurrency = 5) {
  const workingProxies = []
  const failedProxies = []

  // 使用Promise池控制并发
  const batches = []
  for (let i = 0; i < proxyList.length; i += concurrency) {
    batches.push(proxyList.slice(i, i + concurrency))
  }

  for (const batch of batches) {
    const results = await Promise.all(
      batch.map((proxy) => isProxyValid(proxy).then((valid) => ({ proxy, valid })))
    )

    results.forEach(({ proxy, valid }) => {
      if (valid) {
        workingProxies.push(proxy)
      } else {
        failedProxies.push(proxy)
      }
    })
  }

  return {
    total: proxyList.length,
    working: workingProxies.length,
    failed: failedProxies.length,
    workingProxies,
    failedProxies,
    successRate: ((workingProxies.length / proxyList.length) * 100).toFixed(2) + '%'
  }
}
export async function testProxy(proxyUrl) {
  try {
    const response = await fetch('https://httpbin.org/ip', {
      method: 'GET',
      agent: new HttpsProxyAgent(proxyUrl), // 正确用法：直接使用导入的构造函数
      timeout: 3000
    })

    const dataText = await response.text()
    const data = JSON.parse(dataText)
    console.log('testProxy response:', data)
    const proxyHost = new URL(proxyUrl).hostname

    return {
      working: true,
      yourIp: data.origin,
      isProxyIp: data.origin === proxyHost,
      proxyUrl
    }
  } catch (error) {
    return {
      working: false,
      error: error.message,
      proxyUrl
    }
  }
}
// 使用示例
// const proxyList = [
//   'http://proxy1.example.com:8080',
//   'http://proxy2.example.com:3128',
//   'http://proxy3.example.com:8888'
// ]

// testProxyPool(proxyList).then(console.log)
